package com.supermarket.controller;

import com.supermarket.entity.Bill;
import com.supermarket.service.BillService;
import com.supermarket.util.R;
import com.supermarket.util.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/bill")
public class BillController {
    @Autowired
    private BillService billService;

    @GetMapping("/list")
    public R<Object> list(@RequestParam(defaultValue = "1") Integer currentPage,
                          @RequestParam(defaultValue = "10") Integer pageSize,
                          @RequestParam(required = false) String billCode,
                          @RequestParam(required = false) String productName,
                          @RequestParam(required = false) String proName){
        return billService.getBillList(currentPage, pageSize, billCode, productName, proName);
    }

    @GetMapping("/{id}")
    public Bill getBillById(@PathVariable Long id) {
        return billService.getBillById(id);
    }

    @GetMapping("/checkCode")
    public R<Boolean> checkBillCode(@RequestParam String billCode) {
        try {
            boolean isUnique = !billService.existsByBillCode(billCode);
            return R.createSuccess(isUnique);
        } catch (Exception e) {
            return R.createError(StatusCode.ERROR, "检查账单编码失败");
        }
    }

    @PostMapping("/add")
    public R<Void> addBill(@RequestBody Bill bill) {
        try {
            // 检查账单编码是否已存在
            if (billService.existsByBillCode(bill.getBillCode())) {
                return R.createError(StatusCode.ERROR, "账单编码已存在，请使用其他编码");
            }

            // 设置创建时间和默认值
            bill.setCreationDate(new Date());
            if (bill.getIsPayment() == null) {
                bill.setIsPayment(1); // 默认未支付
            }

            // 使用自定义的addBill方法，包含供应商处理逻辑
            billService.addBill(bill);

            // 明确指定成功响应码为"00"以匹配前端期望
            return R.createSuccess("00", "账单添加成功", null);

        } catch (Exception e) {
            e.printStackTrace(); // 添加异常打印
            return R.createError(StatusCode.ERROR, "系统异常: " + e.getMessage());
        }
    }
    
    @PutMapping
    public R<Void> updateBill(@RequestBody Bill bill) {
        billService.updateBill(bill);
        return R.createSuccess();
    }

    @DeleteMapping("/{id}")
    public R<Void> deleteBill(@PathVariable Long id) {
        try {
            billService.deleteBill(id);
            return R.createSuccess();
        } catch (Exception e) {
            return R.createError(StatusCode.ERROR, "删除账单失败，该账单可能已存在关联");
        }
    }
    
    @GetMapping("/stats")
    public R<Map<String, Object>> getDashboardStats() {
        return billService.getDashboardStats();
    }
}
